<template>
  <div class="container">
    <span style="color: red; font-size: 20px;font-weight: 700;">全部商品</span>
    <div class="right" v-if="addressData.length > 0">
      <el-popover placement="left" min-width="400" trigger="hover">
        <el-table :data="addressData">
          <el-table-column min-width="300" property="address" label="地址"></el-table-column>
          <el-table-column label="操作" min-width="150">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleConfirm(scope.$index, scope.row)">确定</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button slot="reference"><i class="iconfont icon-zhuzhi1" style="color: skyblue"></i> {{ selected }}</el-button>
      </el-popover>
    </div>
    <div>
      <el-button class="right" type="primary" @click="dialogFormVisible = true">添加收货地址</el-button>

      <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="收货地址" :label-width="formLabelWidth">
            <el-input v-model="form.address" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="insert">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    address: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      addressData: this.address,
      dialogFormVisible: false,
      form: {
        address: ''
      },
      formLabelWidth: '120px',
      selected: '请选择收货地址'
    }
  },
  methods: {
    handleConfirm(index, row) {
      this.selected = row.address
      this.$emit('deliveryAddr', this.selected)
    },
    insert() {
      if (this.form.address.trim() === '') {
        return
      }
      const obj = {
        address: this.form.address.trim()
      }
      this.addressData.push(obj)
      this.form.address = ''
      this.dialogFormVisible = false
      this.$emit('changeAddr', this.addressData)
    },
    handleDelete(index, row) {
      this.addressData.splice(index, 1)
      this.$emit('changeAddr', this.addressData)
    }
  },
  watch: {
    address: function(val) {
      this.addressData = val
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  max-width: 986px;
  margin: 5px auto;
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  span {
    flex: 5;
  }
  .right {
    flex: 1;
    margin-right: 5px;
  }
}
</style>
